<template>
  <div class="index-container">
    <!-- 搜索条件区域 -->
    <div class="search-box">
      <div class="search-item">
        <span class="search-label">检测项编码</span>
        <el-input
          v-model="searchQuery.index_code"
          placeholder="检测项编码"
        ></el-input>
      </div>

      <div class="search-item">
        <span class="search-label">检测项名称</span>
        <el-input
          v-model="searchQuery.index_name"
          placeholder="检测项名称"
        ></el-input>
      </div>
      
      <div class="search-item">
        <span class="search-label">检测项类型</span>
        <el-select
          v-model="searchQuery.index_type"
          placeholder="请选择检测项类型"
          clearable
          @change="handleSearch"
          :loading="typeLoading"
        >
          <el-option
            v-for="item in itemTypeOptions"
            :key="item.value"
            :label="item.label"
            :value="item.value">
          </el-option>
        </el-select>
      </div>

      
      <div class="search-buttons">
        <el-button type="primary" @click="handleSearch">搜索</el-button>
        <el-button @click="handleReset">重置</el-button>
      </div>
    </div>

    <!-- 操作按钮区域 -->
    <div class="action-buttons">
      <el-button type="primary" @click="openDialog('add')">新增</el-button>
      <el-button 
        type="danger" 
        :disabled="selectedIndexes.length === 0"
        @click="batchDelete"
      >
        批量删除({{ selectedIndexes.length }})
      </el-button>
    </div>

    <!-- 表格区域 -->
    <div class="table-box">
      <el-table 
        ref="indexTable"
        :data="indexList" 
        border 
        style="width: 100%"
        v-loading="loading"
        @selection-change="handleSelectionChange"
      >
        <el-table-column 
          type="selection" 
          width="55"
          :selectable="selectable"
        ></el-table-column>
        <el-table-column prop="index_code" label="检测项编码" min-width="150"></el-table-column>
        <el-table-column prop="index_name" label="检测项名称" width="120"></el-table-column>
        <el-table-column prop="index_type" label="检测项类型" width="120">
          <template slot-scope="scope">
            {{ getIndexTypeName(scope.row.index_type) }}
          </template>
        </el-table-column>
        <el-table-column prop="qc_tool" label="检测工具" width="120">
          <template slot-scope="scope">
            {{ scope.row.qc_tool || '-' }}
          </template>
        </el-table-column>
        <el-table-column prop="qc_result_spc" label="检测单位" min-width="150">
          <template slot-scope="scope">
            {{ scope.row.qc_result_spc || '-' }}
          </template>
        </el-table-column>
        <el-table-column prop="remark" label="备注" min-width="150">
          <template slot-scope="scope">
            {{ scope.row.remark || '-' }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="180" fixed="right">
          <template slot-scope="scope">
            <el-button size="mini" @click="handleEdit(scope.row)">修改</el-button>
            <el-button size="mini" type="danger" @click="handleDelete(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <!-- 分页区域 -->
    <div class="pagination-box">
      <el-pagination
        background
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        :page-sizes="[10, 20, 50, 100]"
        :page-size="size"
        :current-page="current"
        @size-change="handleSizeChange"
        @current-change="handlePageChange"
      />
    </div>

    <!-- 新增/编辑对话框子组件 -->
    <index-dialog
      :visible.sync="dialogVisible"
      :title="dialogTitle"
      :form-data="formData"
      :item-types="itemTypes"
      :is-edit-mode="isEditMode"
      @submit="handleSubmit"
      @submit-success="fetchIndexList"
    />
  </div>
</template>

<script>
import IndexDialog from './IndexDialog.vue'
import request from '@/utils/request'


// 检测项类型映射
const INDEX_TYPE_MAP = {
  1: '尺寸',
  2: '物理性能检测',
  3: '外观',
  4: '化学成分检测',
  5: '环境与耐久性测试',
  6: '工艺性能测试',
  7: '无损检测'
};

export default {
  components: {
    IndexDialog
  },
  data() {
    return {
      itemTypeOptions: Object.entries(INDEX_TYPE_MAP).map(([value, label]) => ({
        value: parseInt(value),
        label
      })),
      isEditMode: false,
      searchQuery: {
        index_code: '',
        index_name: '',
        index_type: '',
      },
      indexList: [],
      selectedIndexes: [],
      total: 0,
      current: 1,
      size: 10,
      itemTypes: [
        '尺寸',
        '物理性能检测',
        '外观',
        '化学成分检测',
        '环境与耐久性测试',
        '工艺性能测试',
        '无损检测',
        '力学性能检测',
        '金相检测',
        '特殊用途检测'
      ],
      loading: false,
      typeLoading: false,
      dialogVisible: false,
      dialogTitle: '添加检测项',
      formData: {
        index_id: null,
        index_code: '',
        index_name: '',
        index_type: '',
        qc_tool: '',
        qc_result_type: '',
        qc_result_spc: '',
        remark: ''
      }
    }
  },
  created() {
    this.initPage()
  },
  methods: {
    getIndexTypeName(value) {
      return INDEX_TYPE_MAP[value] || value;
    },
    async initPage() {
      try {
        this.loading = true
        await this.fetchIndexList()
      } catch (error) {
        this.handleApiError(error, '数据加载失败')
      } finally {
        this.loading = false
      }
    },
    
     async fetchIndexList() {
      try {
        this.loading = true;
        const queryParams = {
          pageNum: this.current,
          pageSize: this.size,
          ...(this.searchQuery.index_code && { index_code: this.searchQuery.index_code }),
          ...(this.searchQuery.index_name && { index_name: this.searchQuery.index_name }),
          ...(this.searchQuery.index_type && { index_type: this.searchQuery.index_type })
        };

        const response = await request({
          url: '/ldzl-qc/qc/qcIndex/selectQcIndexList',
          method: 'post',
          params: queryParams  
        });
        
        this.indexList = response?.records || [];
        this.total = response?.total || 0;
        this.size = response?.size || 10;
        this.current = response?.current || 1;
        this.selectedIndexes = [];
      } catch (error) {
        this.handleApiError(error, '检测项列表加载失败');
      } finally {
        this.loading = false;
      }
    },
    
    handleSearch() {
      this.current = 1
      this.fetchIndexList()
    },
    
    handleReset() {
      this.searchQuery = {
        index_code: '',
        index_name: '',
        index_type: '',
      }
      this.current = 1
      this.fetchIndexList()
    },
    
    handleSelectionChange(val) {
      this.selectedIndexes = val
    },
    
    batchDelete() {
      if (this.selectedIndexes.length === 0) {
        this.$message.warning('请至少选择一项');
        return;
      }
      
      this.$confirm(`确定删除选中的 ${this.selectedIndexes.length} 条记录吗?`, '提示', {
        type: 'warning'
      }).then(async () => {
        try {
          const ids = this.selectedIndexes.map(item => item.index_id);
          
          const response = await request({
            url: '/ldzl-qc/qc/qcIndex/deleteQcIndex',
            method: 'post',
            data: ids
          });
          
          if (response === true || response.success) {
            this.$message.success('批量删除成功');
            this.selectedIndexes = [];
            this.fetchIndexList();
          } else {
            throw new Error(response.message || '批量删除失败');
          }
        } catch (error) {
          console.error('批量删除错误详情:', error);
          this.$message.error(error.message || '批量删除失败');
        }
      }).catch(() => {
        this.$message.info('已取消删除');
      });
    },

    
    selectable(row, index) {
      return true
    },
    
    openDialog(mode = 'add', rowData = null) {
      this.dialogVisible = true
      this.isEditMode = mode === 'edit'
      this.dialogTitle = this.isEditMode ? '编辑检测项' : '添加检测项'
      
      if (this.isEditMode && rowData) {
        this.formData = {
          index_id: rowData.index_id,
          index_code: rowData.index_code,
          index_name: rowData.index_name,
          index_type: rowData.index_type,
          qc_tool: rowData.qc_tool || '',
          qc_result_type: rowData.qc_result_type || '',
          qc_result_spc: rowData.qc_result_spc || '',
          remark: rowData.remark || ''
        }
      } else {
        this.formData = {
          index_id: null,
          index_code: '',
          index_name: '',
          index_type: '',
          qc_tool: '',
          qc_result_type: '',
          qc_result_spc: '',
          remark: ''
        }
      }
    },
    
    handleSubmit(formData) {
      const operation = this.isEditMode ? '修改' : '添加'
      this.$confirm(`确定${operation}该检测项吗?`, '提示', {
        type: 'warning'
      }).then(async () => {
        try {
          const url = this.isEditMode 
            ? '/ldzl-qc/qc/qcIndex/updateQcIndex' 
            : '/ldzl-qc/qc/qcIndex/insertQcIndex'
          
          const response = await request({
            url: url,
            method: 'post',
            data: formData
          })
          
          if (response) {
            this.$message.success(`${operation}成功`)
            this.dialogVisible = false
            this.fetchIndexList()
          } else {
            throw new Error(response?.message || `${operation}失败`)
          }
        } catch (error) {
          this.handleApiError(error, `${operation}失败`)
        }
      }).catch(() => {
        this.$message.info(`已取消${operation}`)
      })
    },
    
    handleEdit(row) {
      this.openDialog('edit', row)
    },
    
    async handleDelete(row) {
      try {
        await this.$confirm('确定删除该记录吗?', '提示', {
          type: 'warning'
        })
        await request({
          url: '/ldzl-qc/qc/qcIndex/deleteQcIndex',
          method: 'post',
          data: [row.index_id]
        })
        this.$message.success('删除成功')
        this.fetchIndexList()
      } catch (error) {
        if (error !== 'cancel') {
          this.handleApiError(error, '删除失败')
        }
      }
    },
    
    handleSizeChange(val) {
      this.size = val
      this.fetchIndexList()
    },
    
    handlePageChange(val) {
      this.current = val
      this.fetchIndexList()
    },
    
    handleApiError(error, defaultMsg = '操作失败') {
      console.error('API Error:', error)
      const msg = error.response?.data?.message || defaultMsg
      this.$message.error(msg)
    }
  }
}
</script>

<style scoped>
.index-container {
  padding: 20px;
  background: #fff;
}

.search-box {
  display: flex;
  flex-wrap: wrap;
  margin-bottom: 20px;
  align-items: center;
}

.search-item {
  display: flex;
  align-items: center;
  margin-right: 15px;
  margin-bottom: 10px;
}

.search-label {
  min-width: 80px;
  text-align: right;
  padding-right: 10px;
  font-size: 14px;
}

.search-buttons {
  margin-left: 15px;
  margin-bottom: 10px;
}

.action-buttons {
  margin-bottom: 20px;
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
}

.table-box {
  margin-top: 20px;
}

.pagination-box {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}
</style>